// 社团路由
const express = require('express');
const router = express.Router();
const Association = require('../models/Association');
const AssociationMember = require('../models/AssociationMember');
const User = require('../models/User');
const { Op } = require('sequelize');

/**
 * 获取社团列表
 * @route GET /api/associations
 * @description 获取社团列表，支持分页和搜索
 * @access Public
 */
router.get('/', async (req, res) => {
  try {
    const { page = 1, size = 10, keyword = '', category = '' } = req.query;
    const offset = (page - 1) * size;
    
    const whereCondition = {
      status: 1 // 只返回正常状态的社团
    };
    
    // 关键词搜索
    if (keyword) {
      whereCondition.name = {
        [Op.like]: `%${keyword}%`
      };
    }
    
    // 分类筛选
    if (category && category !== '全部') {
      whereCondition.category = category;
    }
    
    const { count, rows } = await Association.findAndCountAll({
      where: whereCondition,
      include: [{
        model: User,
        as: 'president',
        attributes: ['nickName', 'avatarUrl']
      }],
      limit: parseInt(size),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });
    
    res.status(200).json({
      success: true,
      data: rows,
      total: count,
      page: parseInt(page),
      totalPages: Math.ceil(count / size)
    });
  } catch (error) {
    console.error('获取社团列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 获取社团详情
 * @route GET /api/associations/:id
 * @description 获取单个社团的详细信息
 * @access Public
 */
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const association = await Association.findByPk(id, {
      include: [{
        model: User,
        as: 'president',
        attributes: ['nickName', 'avatarUrl']
      }]
    });
    
    if (!association) {
      return res.status(404).json({ message: '社团不存在' });
    }
    
    res.status(200).json({ success: true, data: association });
  } catch (error) {
    console.error('获取社团详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 创建社团
 * @route POST /api/associations
 * @description 创建新社团
 * @access Private
 */
router.post('/', async (req, res) => {
  try {
    const userId = req.user?.id || 1; // 临时处理，实际应用中应从token中获取
    const { name, description, category, contactPhone, contactEmail } = req.body;
    
    // 验证必填字段
    if (!name || !description || !category) {
      return res.status(400).json({ message: '缺少必要的社团信息' });
    }
    
    // 检查社团名称是否已存在
    const existingAssociation = await Association.findOne({ where: { name } });
    if (existingAssociation) {
      return res.status(400).json({ message: '该社团名称已存在' });
    }
    
    // 创建社团
    const association = await Association.create({
      name,
      description,
      category,
      presidentId: userId,
      contactPhone,
      contactEmail,
      memberCount: 1,
      establishDate: new Date()
    });
    
    // 创建社团成员记录
    await AssociationMember.create({
      userId,
      associationId: association.id,
      role: 'president'
    });
    
    res.status(201).json({ success: true, data: association, message: '社团创建成功' });
  } catch (error) {
    console.error('创建社团失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 加入社团
 * @route POST /api/associations/:id/join
 * @description 用户申请加入社团
 * @access Private
 */
router.post('/:id/join', async (req, res) => {
  try {
    const userId = req.user?.id || 1; // 临时处理，实际应用中应从token中获取
    const { id } = req.params;
    const { applyReason } = req.body;
    
    // 检查社团是否存在
    const association = await Association.findByPk(id);
    if (!association) {
      return res.status(404).json({ message: '社团不存在' });
    }
    
    // 检查用户是否已经是社团成员
    const existingMember = await AssociationMember.findOne({
      where: {
        userId,
        associationId: id,
        status: { [Op.ne]: 3 } // 排除已退出的状态
      }
    });
    
    if (existingMember) {
      return res.status(400).json({ message: '您已经是该社团成员或申请正在处理中' });
    }
    
    // 创建加入申请
    await AssociationMember.create({
      userId,
      associationId: id,
      role: 'member',
      status: 2 // 申请中状态
    });
    
    res.status(200).json({ success: true, message: '申请已提交，请等待审核' });
  } catch (error) {
    console.error('加入社团失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 获取用户加入的社团
 * @route GET /api/associations/user/:userId
 * @description 获取用户加入的社团列表
 * @access Private
 */
router.get('/user/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const userAssociations = await AssociationMember.findAll({
      where: {
        userId,
        status: 1 // 只返回正常状态的成员
      },
      include: [{
        model: Association,
        attributes: ['id', 'name', 'logo', 'description', 'category', 'memberCount']
      }],
      order: [['joinDate', 'DESC']]
    });
    
    // 格式化返回数据
    const result = userAssociations.map(item => ({
      id: item.association.id,
      name: item.association.name,
      logo: item.association.logo,
      description: item.association.description,
      category: item.association.category,
      memberCount: item.association.memberCount,
      role: item.role,
      joinDate: item.joinDate
    }));
    
    res.status(200).json({ success: true, data: result });
  } catch (error) {
    console.error('获取用户社团列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router;